import React, { PureComponent } from 'react';
import Cropper, { ReactCropperElement } from 'react-cropper';
import { Modal, Button, message } from 'antd';
import { getToken, getMd5 } from '@/utils/utils';
import { fingerprintFetch } from '@/utils/request'

import 'cropperjs/dist/cropper.css';
// const defaultSrc =
//   'https://raw.githubusercontent.com/roadmanfong/react-cropper/master/example/img/child.jpg';

export default class PateoCropper extends PureComponent<any, any> {
  cropperRef = React.createRef<ReactCropperElement>();

  constructor(props: any) {
    super(props);
    this.state = {
      image: '',
    };
  }

  componentDidMount() {
    if (!this.props.image) {
      return;
    }
    let md5 = getMd5(`strUrl=${this.props.image}`);
    fingerprintFetch(`${window.g.url}/common/download?strUrl=${encodeURIComponent(this.props.image)}`, {
      headers: {
        responseType: 'arraybuffer',
        shaSign: md5,
        OptAuthorization: `${getToken()}`,
      },
    })
      .then(response => {
        if (response.status === 200) {
          return response.arrayBuffer();
        } else {
          throw response;
        }
      })
      .then(buffer => {
        const blob = new Blob([buffer], { type: 'image/jpg' });
        const fileReader = new FileReader();
        fileReader.onload = e => {
          console.log('@@', e?.target?.result);
          this.setState({ image: e?.target?.result });
        };
        fileReader.readAsDataURL(blob);
      })
      .catch(() => {});
  }

  handleOk = async (e: any) => {
    e.preventDefault();
    let back = false;
    const { handleOk } = this.props;
    if (handleOk) {
      if (typeof this.cropperRef.current?.cropper !== 'undefined') {
        back = await handleOk(this.cropperRef.current?.cropper.getCroppedCanvas());
      }
    }
    back && this.handleCancel();
  };
  handleCancel = () => {
    const { changeVisible } = this.props;
    this.setState({
      image: '',
    });
    changeVisible && changeVisible();
  };
  onChange = (e: any) => {
    //限制上传图片大小
    const { changeSize } = this.props;

    let files;
    console.log('files[0]', e);
    if (e.dataTransfer) {
      files = e.dataTransfer.files;
    } else if (e.target) {
      files = e.target.files;
    }
    if (changeSize) {
      if (!files[0]) {
        return;
      }
      console.log('changeSize', changeSize, files[0]);
      const size = files[0].size / 1024;
      if (size > changeSize) {
        message.error(`图片大小不能大于 ${changeSize}KB`);
        return;
      }
    }
    e.preventDefault();
    const reader = new FileReader();
    reader.onload = () => {
      this.setState({
        image: reader.result as any,
      });
    };
    console.log('files[0]', files[0]);
    if (files[0]) {
      reader.readAsDataURL(files[0]);
    }
  };

  render() {
    const { visible, modalTitle } = this.props;
    const { image } = this.state;

    return (
      <Modal
        visible={visible}
        title={modalTitle}
        width={800}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        footer={[
          <Button key="back" type="ghost" size="large" onClick={this.handleCancel}>
            取 消
          </Button>,
          <Button key="submit" type="primary" size="large" onClick={this.handleOk}>
            提 交
          </Button>,
        ]}
      >
        <div>
          <div style={{ width: '100%' }}>
            <input
              type="file"
              onChange={this.onChange}
              onClick={() => {
                this.setState({ tips: '请稍后' });
              }}
            />
            <br />
            <br />
            {image ? (
              <Cropper
                ref={this.cropperRef}
                style={{ height: 400, width: '100%' }}
                // zoomTo={0.5}
                // initialAspectRatio={1}
                // preview=".img-preview"
                src={image}
                aspectRatio={this.props.aspectRatio}
                // minCropBoxHeight={10}
                // minCropBoxWidth={10}
                // background={false}
                // responsive={true}
                autoCropArea={1}
                // checkOrientation={false} // https://github.com/fengyuanchen/cropperjs/issues/671
                // guides={true}
                cropBoxMovable={false}
                cropBoxResizable={false}
                // zoomOnTouch={false}
                // movable={false}
                dragMode="move"
                // viewMode={1}
              />
            ) : (
              <div style={{ height: 400, width: '100%', textAlign: 'center', lineHeight: '400px' }}>
                请从左上角选择文件
              </div>
            )}
          </div>
        </div>
      </Modal>
    );
  }
}
